<?php

namespace App\Middleware;

use App\Constants\Keywords;
use Hyperf\Context\Context;
use Hyperf\Rpc\Context as RpcContext;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class HttpContext implements MiddlewareInterface
{
    protected ContainerInterface $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        //如果没有request_id 则增加
        $request_id = $request->getHeaderLine("X-Request-Id") ?: uniqid();
        Context::set(Keywords::REQUEST_ID,$request_id);

        //获取语言设置，如果没有就取默认
        $lang = $request->getHeaderLine("Locale") ?: \Hyperf\Config\config("translation.locale") ;
        Context::set(Keywords::LANG,$lang);

        //为json-rpc设置上下文
        $this->container->get(RpcContext::class)->setData([
            Keywords::LANG => $lang,
            Keywords::REQUEST_ID => $request_id
        ]);

        return $handler->handle($request);
    }
}
